package com.lz.concurrent;

import java.util.Vector;

/**
 * AbsoluteSafeDemo..
 *
 * @author Lizhong
 * @date 2019/3/25
 */
public class AbsoluteSafeDemo {
    private static Vector<Integer> vector = new
            Vector<>();

    volatile static boolean flag = true;

    /**
     *  虽然Vector方法中每个方法是同步的，But 第二个线程vector.size(),与vector.get()判断是有误差的,并非原子操作
     * @see {@link java.util.concurrent.ConcurrentHashMap } 有读写操作时，也要加@Synchronize关键字
     *  Exception in thread "Thread-14" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 245
     */
    public static void main(String[] args) throws InterruptedException {

        while (flag) {
            for (int i = 0; i < 50; i++) vector.add(i);

            Thread thread01 = new Thread(() -> {
                for (int i = vector.size() - 1; i >= 0; i--) {
                    vector.remove(i);
                }
            });


            Thread thread02 = new Thread(() -> {
                for (int i = 0; i < vector.size(); i++) {
                    try {
                        Integer integer = vector.get(i);
                        System.out.println(Thread.currentThread().getId() + ":   \t" + integer);
                    } catch (Exception e) {

                        flag = false;
                        throw e;
                    }
                }
            });

            thread01.start();


            thread02.start();
            while (Thread.activeCount() > 20) {
            }

        }
    }
}
